#!/usr/bin/env python

# This script plots the distribution of the gop data.
#
# Inputs (given as arguments): video1_framestats.txt, video2_framestats.txt, etc...
# Output Plot #3: Distribution of GOP data size (for each file given)
#
#  To Do:
#	- Verify x-axis scaling

import numpy as np
import pylab as pl # Plotting
import os.path as osp # path
import sys # Handling command line arguments
from matplotlib.font_manager import FontProperties as FP # Font formatting in plots

# Helper function for analysing *_framestats.txt logs.

def new_frame(filep):
	line = '1'
	while not line.startswith('[/FRAME]'):
		line = filep.readline()
		if line.startswith('pkt_pos='):
			pos = int(line[line.find('=')+1:])
		if line.startswith('pict_type='):
			pict_type = line[line.find('=')+1:-1]
	return pos, pict_type

# Plotter function, is called with a reference to a *_framestats.txt file and a reference number.

def plot(filep,video_nb):

	##### DATA EXTRACTION #####

	pos_type = []

	line = '1'
	while line:
		line = f.readline()
		if line.startswith('[FRAME]'):
			position, pict_type = new_frame(f)
			pos_type.append((position, pict_type))

	# Prepare to build a list containing the data sizes of all GOP in video
	gopsize_list=[]
	gop_temp_size=0
	i_ref=0

	# Build gop_size_list 
	for i in range(len(pos_type)-1)	:
		if (str(pos_type[i+1][1]).lower()=='i'):
			gop_temp_size=pos_type[i][0]-pos_type[i_ref][0]
			gopsize_list.append(gop_temp_size)
			i_ref=i

	# Scale gop_size_list to kbytes - can be included in above loop
	for i in range(len(gopsize_list)): 	
		gopsize_list[i]=gopsize_list[i]/1000.

	# Parameters for the histogram
	histogram_bin_size = 50 # Carefully chosen :)
	max_size=3000 # [kB] since we have normalized gop sizes relative to total filesize
	min_size=0

	# Check if we chose max_size properly
	if max_size<max(gopsize_list):
		print 'WARNING: We are missing some GOP in the Plot, increase max_size [kB]'

	total_size=pos_type[-1][0]/float(1000)

	# We are no longer normalizing x
	norm_gopsize_list=gopsize_list
	
	# make histogram of data
	hist_gopsize = pl.histogram(norm_gopsize_list, histogram_bin_size, (min_size, max_size))

	# Normalizing y data
	norm_hist_gopsize_y=[]
	nb_gops=np.sum(hist_gopsize[0])
	for i in range(len(hist_gopsize[0])):
		norm_hist_gopsize_y.append(hist_gopsize[0][i]/float(nb_gops))

	# Histogram data is already normalized - just calling it something else
	norm_hist_gopsize_x=hist_gopsize[1][:-1]

	# Write the same data to a file
	logfile.write('Video '+str(video_nb+1)+'\n')
	logfile.write('Filesize '+str(total_size/1000.)+' MB'+'\n')
	logfile.write('Number of gops '+str(nb_gops)+'\n')
	logfile.write('Mean GOP size '+str(np.mean(gopsize_list))+'kB'+'\n')
	logfile.write('GOP max size '+str(np.max(gopsize_list))+'kB'+'\n')
	logfile.write('GOP min size '+str(np.min(gopsize_list))+'kB'+'\n')
	logfile.write('\n')	

if __name__ == '__main__':
	
	# Logfile for GOP info about videos
	logfile=open('data/gop_log.txt','w'+'\n')

	# Run through all of the given gopstats.txt logfiles given as arguments
	for arg in range(len(sys.argv)-1):
		input_filename = sys.argv[arg+1]
		f = open(input_filename,'r')
		plot(f,arg)
	
	# Close log file
	logfile.close()



